import { VuexModule, Module, Mutation, Action, getModule } from 'vuex-module-decorators'
import { Erc20ABI } from '@/contract'
import { ethers } from "ethers";
import { toWei } from '@/utils/format'
import store from '@/store'

export interface IErc20State {
    DOGE: string
}

@Module({ dynamic: true, store, name: 'Erc20' })
class Erc20 extends VuexModule implements IErc20State {
    DOGE = ''

    @Mutation
    SET_DOGE(DOGE: string) {
        this.DOGE = DOGE
    }

    @Action({ rawError: true })
    public totalSupply(owner: string): Promise<string> {
        const contract = new store.getters.web3.eth.Contract(Erc20ABI, owner);
        return contract.methods.totalSupply().call()
    }

    @Action({ rawError: true })
    public balanceOf({ owner, spender = store.getters.userAddr }: any): Promise<string> {
        const contract = new store.getters.web3.eth.Contract(Erc20ABI, owner);
        return contract.methods.balanceOf(spender).call()
    }

    @Action({ rawError: true })
    public async allowance({ owner, spender }: { owner: string; spender: string }): Promise<string> {
        const contract = new store.getters.web3.eth.Contract(Erc20ABI, owner);
        return contract.methods.allowance(store.getters.userAddr, spender).call()
    }

    @Action({ rawError: true })
    public async approve(item: any): Promise<any> {
        const ethersProvider = new ethers.providers.Web3Provider(
            window.ethereum,
            "any"
        );
        const contract = new ethers.Contract(
            item.owner,
            Erc20ABI,
            ethersProvider.getSigner()
        );
        const message = {
            from: store.getters.userAddr,
            gasLimit: 90000,
            // gasPrice: '10000000000',
        }
        const appValue = store.getters.web3.utils.toTwosComplement(-1);
        const result = await contract.approve(
            item.spender,
            toWei(item.appValue) || appValue,
            message
        );
        return result.wait()
    }

    // @Action({ rawError: true })
    // public transfer({ value, sendAddress, owner }: { value: string, sendAddress: string, owner: string }): Promise<any> {
    //     const contract = new store.getters.web3.eth.Contract(Erc20ABI, owner);
    //     const message = {
    //         from: store.getters.userAddr,
    //         to: sendAddress
    //     }
    //     return contract.methods.transfer(sendAddress, store.getters.web3.utils.toWei(value, 'lovelace')).send(message)
    // }
}

export const Erc20Module = getModule(Erc20)